﻿using System;
using Wedonek.Demo.RemoteModel.Msg;
using Wedonek.Demo.RemoteModel.Order;
using Wedonek.Demo.RemoteModel.Order.Model;
using Wedonek.Demo.RemoteModel.User;
using Wedonek.Gateway.Modular.Interface;
using Wedonek.Gateway.Modular.Model;
using WeDonekRpc.ApiGateway.Attr;
using WeDonekRpc.ApiGateway.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Client.Tran;
using WeDonekRpc.Helper;
using WeDonekRpc.HttpApiGateway.Interface;
using WeDonekRpc.Model;
using WeDonekRpc.Modular;

namespace Wedonek.Gateway.Modular.Service
{
    /// <summary>
    /// 订单接口
    /// </summary>
    [ApiPrower("demo.order")]
    internal class OrderService : IOrderService, IApiGateway
    {
        /// <summary>
        /// 添加订单
        /// </summary>
        /// <param name="state">用户登陆状态</param>
        /// <param name="add">添加订单参数</param>
        /// <param name="identity">客户端标识</param>
        /// <returns>订单Id</returns>
        public Guid AddOrder (IUserState state, OrderParam add, IClientIdentity identity)
        {
            string orderNo = Tools.GetSerialNo("DE01");
            Guid id;
            long userId = state.GetValue<long>("UserId");
            using (IRpcTransaction tran = new RpcTransaction())
            {
                id = new AddOrder
                {
                    OrderNo = orderNo,
                    OrderPrice = add.OrderPrice,
                    OrderTitle = add.OrderTitle,
                    UserId = userId
                }.Send();
                new LockUserMoney
                {
                    Money = 1,
                    UserId = userId
                }.Send();
                new PlaceAnOrder
                {
                    OrderNo = orderNo,
                    UserId = userId
                }.Send();
                tran.Complate();//提交事务
            }
            return id;
        }
        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="orderId">订单Id</param>
        public void DropOrder (Guid orderId)
        {
            new DropOrder { OrderId = orderId }.Send();
        }
        /// <summary>
        /// 获取订单
        /// </summary>
        /// <param name="orderId">订单Id</param>
        /// <returns>订单信息</returns>
        public OrderData GetOrder (Guid orderId)
        {
            return new GetOrder { OrderId = orderId }.Send();
        }
        /// <summary>
        /// 查询订单
        /// </summary>
        /// <param name="state">订单状态</param>
        /// <param name="paging">分页信息</param>
        /// <param name="count">订单数</param>
        /// <returns>订单信息</returns>
        public PagingResult<OrderData> Query (IUserState state, BasicPage paging)
        {
            return new QueryOrder
            {
                Index = paging.Index,
                Size = paging.Size,
                NextId = paging.NextId,
                UserId = state.GetValue<long>("UserId")
            }.Send();
        }
    }
}
